using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using PT.Common;

namespace PT.BLL;

/// <summary>
/// ModelScope API
/// </summary>
public static class ModelScopeService
{
    private static readonly string ApiKey = GetApiKey(); // 您的ModelScope Token
    private static readonly string ModelId = "deepseek-ai/DeepSeek-V3.1"; // ModelScope Model-Id
    private static readonly string ApiUrl = "https://api-inference.modelscope.cn/v1/chat/completions"; // ModelScope API端点

    private static string GetApiKey()
    {
        try
        {
            return getHostConfig.ModelScopeApiKey;
        }
        catch
        {
            // 出现异常时返回默认值
            return "";
        }
    }

    /// <summary>
    /// 调用ModelScope API并获取响应（静态方法）
    /// </summary>
    /// <param name="userMessage">用户消息内容</param>
    /// <returns>包含推理内容和最终答案的元组</returns>
    public static async Task<(string ReasoningContent, string Content)> GetModelScopeResponseAsync(string userMessage)
    {
        using var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {ApiKey}");

        Console.WriteLine($"使用ModelScope API，ModelId：{ModelId}，ApiKey：{ApiKey}");

        // 构造请求数据
        var requestData = new
        {
            model = ModelId,
            messages = new[]
            {
                new { role = "user", content = userMessage }
            },
            stream = false
        };

        // 序列化请求数据
        var jsonRequest = JsonSerializer.Serialize(requestData);
        var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

        try
        {
            // 发送POST请求
            var response = await httpClient.PostAsync(ApiUrl, content);

            if (response.IsSuccessStatusCode)
            {
                // 读取并解析响应
                var jsonResponse = await response.Content.ReadAsStringAsync();
                using JsonDocument document = JsonDocument.Parse(jsonResponse);
                var root = document.RootElement;

                // 提取choices中的message
                var choices = root.GetProperty("choices");
                var firstChoice = choices[0];
                var message = firstChoice.GetProperty("message");

                // 获取reasoning_content和content
                string reasoningContent = string.Empty;
                string finalContent = string.Empty;

                if (message.TryGetProperty("reasoning_content", out var reasoningContentElement))
                {
                    reasoningContent = reasoningContentElement.GetString() ?? string.Empty;
                }

                if (message.TryGetProperty("content", out var contentElement))
                {
                    finalContent = contentElement.GetString() ?? string.Empty;
                }

                return (reasoningContent, finalContent);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                throw new HttpRequestException($"请求失败，状态码：{(int)response.StatusCode} - {response.ReasonPhrase}。错误详情：{errorContent}");
            }
        }
        catch (Exception ex)
        {
            throw new Exception($"调用ModelScope API时发生异常：{ex.Message}", ex);
        }
    }

    /// <summary>
    /// 打印ModelScope API的响应结果（静态方法）
    /// </summary>
    /// <param name="userMessage">用户消息内容</param>
    public static async Task PrintModelScopeResponseAsync(string userMessage)
    {
        try
        {
            var result = await GetModelScopeResponseAsync(userMessage);

            if (!string.IsNullOrEmpty(result.ReasoningContent))
            {
                Console.WriteLine("\n\n === 推理内容 ===\n");
                Console.WriteLine(result.ReasoningContent);
            }

            Console.WriteLine("\n\n === 最终答案 ===\n");
            Console.WriteLine(result.Content);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误：{ex.Message}");
        }
    }

    // 使用示例

    static async Task MainTest(string[] args)
    {
        // 使用静态方法调用
        await ModelScopeService.PrintModelScopeResponseAsync("你好");

        // 或者获取详细结果自行处理
        var result = await ModelScopeService.GetModelScopeResponseAsync("你好");
        Console.WriteLine($"推理内容：{result.ReasoningContent}");
        Console.WriteLine($"最终答案：{result.Content}");
    }

    

    
}


